package com.mspbots.rule.exceptions.cw;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.mspbots.cw.request.TenantTicketDTO;
import com.mspbots.cw.request.TenantTimeEntryDTO;
import lombok.extern.slf4j.Slf4j;
import org.jeasy.rules.annotation.Action;
import org.jeasy.rules.annotation.Condition;
import org.jeasy.rules.annotation.Fact;
import org.jeasy.rules.annotation.Rule;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.util.UriComponentsBuilder;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/**
 * com.mspbots.rule.exceptions.timeentry.IncludingWords
 *
 * @author houzhongfei
 * @date 12:42 2019/11/5
 **/
@Slf4j
@Rule(name = "IncludingWords", description = "Time log entry has “xxx” in it.")
public class IncludingWordsWithDrools extends CwBaseRule implements IcwBaseRule {


    @Autowired
    RestTemplate restTemplate;

    private String word = "";

    @Condition
    @Override
    public boolean condition(@Fact(FACT) TenantTimeEntryDTO entry) {

        //根据tenantId,ruleId 获取到 drools script
        String ruleScript = getDroolsScript(entry.getTenantId(), this.tenantRuleDTO.getRuleId());
        //调用规则服务判断是否符合规则
//        checkRule(entry, ruleScript);

        try {

            if (!setUserMapping(entry.getTenantUserId()) || super.checkMessage(entry)) {
                return false;
            }
            JsonNode params = JSONUtil.isNull(this.tenantRuleDTO.getRuleParams()) ?
                    this.tenantRuleDTO.getSysParams() : this.tenantRuleDTO.getRuleParams();
            Iterator<String> iterator = params.fieldNames();
            boolean include = false;
            while (iterator.hasNext()) {
                String fieldName = iterator.next();
                String fieldValue = params.get(fieldName).asText().toLowerCase();
                if (StringUtils.isEmpty(fieldValue)) {
                    continue;
                }
                include = include || entry.getDescription().toLowerCase().contains(fieldValue);
                if (include) {
                    word = params.get(fieldName).asText();
                    break;
                }
            }
            String chargeToId = "chargeToId";
            if (include && !ObjectUtils.isEmpty(entry.getExtend().get(chargeToId))) {
                Map<String, Object> ticketsParams = Map.of("tenantId", entry.getTenantId(),
                        "cwId", entry.getExtend().get(chargeToId));
                TenantTicketDTO tenantTicketDTO = this.coreClient.get("/tickets/detail", ticketsParams, TenantTicketDTO.class).block();
                String board = "board";
                if (tenantTicketDTO == null || StringUtils.isEmpty(tenantTicketDTO.getExtend().findPath(board))) {
                    log.info("IncludingWords tenantTicketDTO_is null or status is null {}", entry.getId());
                }
                return tenantTicketDTO.getExtend().findPath(board).get("name").asText().toLowerCase().indexOf("reactive") > -1;
            }
            return false;
        } catch (Exception e) {
            log.error("IncludingWords rule execute error [{}] : {}", e.getStackTrace()[0].getLineNumber(), e.getMessage());
            e.printStackTrace();
        }
        return false;
    }

    private boolean checkRule(TenantTimeEntryDTO entry, String ruleScript) throws JsonProcessingException {
        String url = "http://192.168.1.23:8086/trigger/rule/includingWrordsRule";

        ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.writeValueAsString(entry.toString());

        return false;
    }

    @Action
    @Override
    public void action(@Fact(FACT) TenantTimeEntryDTO entry) {
        messages.setTimeEntryId(entry.getCwTid());
        Map params = new HashMap(16);
        params.put("WORD", styleParam(word));
        String message = getMessage(entry);
        if (message != null) {
            String msg = StrUtil.format(message, params);
            messages.setMessage(msg);
            insertMessage();
        }


    }

    private String getDroolsScript(Long tenantId, Long ruleId) {

        String url = "http://192.168.1.23:8086/trigger/rule/info";
        UriComponentsBuilder urlBuilder = UriComponentsBuilder.fromHttpUrl(url);
        Map<String, String> map = new HashMap();
        map.put("tenantId", tenantId.toString());
        map.put("ruleId", ruleId.toString());
        String targetUrl = urlBuilder.build().encode().toString();
        map.entrySet().stream().forEach(o -> urlBuilder.queryParam(o.getKey(), o.getValue()));
        ResponseEntity<String> forEntity = restTemplate.getForEntity(targetUrl, String.class);
        String droolsScript = (String) JSONUtil.parseObj(forEntity.getBody()).get("content");
        log.info("Drools Script: {}", droolsScript);
        return droolsScript;
    }
}
